package com.example.lambda.Fork;


import java.util.concurrent.RecursiveTask;

// RecursiveAction 无返回值   RecursiveTask 有返回值

public class ForkJoinCalculate extends RecursiveTask<Long> {

    private static final long serialVersionUID = 123456789L;

    private final long start;

    private final long end ;

    public ForkJoinCalculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    private static final long THRESHOLD = 10000;

    @Override
    protected Long compute() {
        long length = end -start;
        if(length<=THRESHOLD){
            long sum = 0;
            for (long i =start;i<end;i++){
                sum += i;
            }
            return sum;
        }else {
            long middle = (start+end) /2 ;
            ForkJoinCalculate left = new ForkJoinCalculate(start,middle);
            left.fork();   // 拆分子任务，压入线程栈
            ForkJoinCalculate right = new ForkJoinCalculate(middle,end);
            right.fork();
            return left.join()+right.join();
        }
    }
}
